<?php
/**
 * 退款处理
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-07
 * Time: 15:02
 */

namespace App\Services\Manager;


use App\Libs\Contracts\PayMent\AliPay\AliWeb;
use App\Libs\Contracts\PayMent\Wxpay\Refund;
use App\Models\BalanceLog;
use App\Models\Income;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\OrderRefund;
use App\Models\UserExtent;
use App\Models\User;
use App\Models\UserCourse;
use App\Models\UserScoreLog;
use App\Services\Front\UserScoreService;

class RefundService
{
    /**
     * 开始退款 原路返回
     * @param $order  orderNo 订单号、payType原支付方式
     * @param $type  1 代表最后一笔订单
     * @return bool
     * @throws \Exception
     */
    public function onLineRefund($order, $type=0, $postage=0)
    {
        //开始退款
        $totalPrice = 0 ;
        $refund = OrderRefund::find($order['refundId']);
        if(!$refund){
            throw new \Exception("退款参数错误");
        }
        if($type){
            $totalPrice = $refund['refundPrice'] + $postage;
        }else{
            $totalPrice = $refund['refundPrice'];
        }
        $refundPayType = $order['payType'];
        //修改状态
        $result['orderNo'] = $order['orderNo'];
        $result['refundNo'] = $refund['refundNo'];
        $result['totalPrice'] = $order['totalPrice'];
        $result['refundPrice'] = $totalPrice;
        //退款
        if($refundPayType === "WX"){//微信退款
            $model = new Refund();
            $model->refund($result);
        }
        if($refundPayType === "PAID"){
            $model = new Refund();
            
            $model->refund($result);
        }
        if($refundPayType === "YANGBEI"){
            User::where('userId',$refund['userId'])->increment('regimenMoney',$refund['refundPrice']);
            User::where('userId',$refund['userId'])->increment('regimenAllMoney',$refund['refundPrice']);
            $tmp['userId'] = $refund['userId'];
            $tmp['title'] = '退款';
            $tmp['createTime'] = date('Y-m-d H:i:s');
            $tmp['score'] = $refund['refundPrice'];
            $tmp['numberStatus'] = 1;
            $tmp['orderNo'] = $refund['refundNo'];
            $tmp['scoreStatus'] = 'YANGBEI';
            UserScoreLog::create($tmp);
            $order1 = Order::where('orderNo',$refund['orderNo'])->first();
            $refund = OrderRefund::where('refundNo',$refund['refundNo'])->first();
            $detail = OrderDetail::where('detailId',$refund['orderDetailId'])->first();
            UserScoreService::decrementYangbeiByOrder($refund['orderNo'],$order1['userId'],$detail['totalPrice']);
            UserScoreService::decrementScore($refund['orderNo'],$order1['userId'],$detail['totalPrice']);
        }
        if($refundPayType === "SCORE"){
            User::where('userId',$refund['userId'])->increment('healthMoney',$refund['refundPrice']);
        }

        /*else{//支付宝退款
            $model = new AliWeb();
            $result['orderNo'] = $order['orderNo'];
            $result['refundPrice'] = $totalPrice / 100;
            $result['refundReason'] = $refund['refundReason'];
            $result['refundNo'] = $refund['refundNo'];
            $model->refund($result);
        }*/

        if($type){
            $status = OrderRefund::where(['refundId'=>$order['refundId']])->update(['refundStatus'=>'SUCCEEDED','postage'=>$postage,'finishTime'=>date("Y-m-d H:i:s",time())]);
        }else{
            $status = OrderRefund::where(['refundId'=>$order['refundId']])->update(['refundStatus'=>'SUCCEEDED']);
        }
        if(!$status){
            throw new \Exception("修改退款状态失败");
        }
        return true;
    }
    /**
     * 开始退款 原路返回
     * @param $order  orderNo 订单号、payType原支付方式
     * @param $type  1 代表最后一笔订单
     * @return bool
     * @throws \Exception
     */
    public function refundOnline($orderNo,$refundPrice)
    {
        //开始退款
        $totalPrice = 0 ;
        $order = Order::where('orderNo',$orderNo)->first();
        $refundNo = getOrderSn("T");
        $refundPayType = $order['payType'];
        //修改状态
        $result['orderNo'] = $order['orderNo'];
        $result['refundNo'] = $refundNo;
        $result['totalPrice'] = $order['totalPrice'];
        $result['refundPrice'] = $refundPrice;
        Order::where('orderId',$order['orderId'])->update(['refundNo'=>$refundNo]);

        //退款
        if($refundPayType === "WX"){//微信退款
            $model = new Refund();
            $model->refund($result);
        }elseif($refundPayType === "BALANCE"){
            User::where('userId',$order['userId'])->increment('balance',$refundPrice);

        }else{//支付宝退款
            $model = new AliWeb();
            $result['orderNo'] = $order['orderNo'];
            $result['refundPrice'] = $totalPrice / 100;
            $result['refundReason'] = $order['refundReason'];
            $result['refundNo'] = $refundNo;
            $model->refund($result);
        }

        $status = Order::where(['orderNo'=>$order['orderNo']])->update(['refundStatus'=>0,"orderStatus"=>"REFUND",'commentStatus'=>'NOT']);
        UserCourse::where(['orderNo'=>$orderNo])->update(['orderCourseStatus'=>'REFUND']);
        Income::where('orderNo',$order['orderNo'])->update(['freezeStatus'=>'REFUND']);
        $balance = BalanceLog::select('changePrice','userId','balanceLogType')->where(['orderNo'=>$orderNo,'freezeStatus'=>'UN_ACOUNT'])->get()->toArray();
        foreach ($balance as $key => $value) {
            if($value['balanceLogType'] == 'COMMOSSION'){
                UserExtent::where('userId',$value['userId'])->update([
                    'distributionBalance' => \DB::raw('distributionBalance - '.$value['changePrice']),
                    'freezeBalance' => \DB::raw('freezeBalance - '.$value['changePrice']),
                    'incomeBalance' => \DB::raw('incomeBalance - '.$value['changePrice'])
                ]);
            }elseif($value['balanceLogType'] == "COURSE_INCOME"){
                UserExtent::where('userId',$value['userId'])->update([
                    'freezeBalance' => \DB::raw('freezeBalance - '.$value['changePrice']),
                    'incomeBalance' => \DB::raw('incomeBalance - '.$value['changePrice'])
                ]);
            }

        }
        BalanceLog::where(['orderNo'=>$orderNo,'freezeStatus'=>'UN_ACOUNT'])->update(['freezeStatus'=>'REFUND']);
        BalanceLog::where(['orderNo'=>$orderNo,'balanceLogType'=>'COURSE'])->update(['freezeStatus'=>'REFUND']);
        if(!$status){
            throw new \Exception("修改退款状态失败");
        }
        return true;
    }
    /**
     * 修改订单状态
     * @param $order
     * @return bool
     * @throws \Exception
     */
    public function updateOrder($order)
    {
        $status = Order::where(['orderNo'=>$order['orderNo']])->first();
        if(!$status){
            throw new \Exception("订单号错误");
        }
        if($status['orderStatus'] === 'WAITREFUND') {//证明全部退款，需要修改订单状态
            if($status['deliverNo']){//证明已经发货，返回到待收货状态
                $orderStatus = Order::where('orderNo',$order['orderNo'])->update(['orderStatus'=>'WAITRECEIVE']);
                if(!$orderStatus){
                    throw new \Exception("修改订单状态失败");
                }
            }else{//没有发货，返回到发货状态
                $orderStatus = Order::where('orderNo',$order['orderNo'])->update(['orderStatus'=>'WAITDELIVER']);
                if(!$orderStatus){
                    throw new \Exception("修改订单状态失败");
                }
            }
        }

        return true;
    }
}